import {SettingType} from "../options/system";


export const navigateTo = (path) => {
    uni.navigateTo({
        url: path
    })
}

export const getTime = (time) => {
    return new Date(time).getTime()
}

export function imgPreview(url: array) {
    uni.previewImage({
        urls: url,
        longPressActions: {
            itemList: ['保存图片'],
            success: function (data: any) {
                console.log(data)
                // saveImageToPhotosAlbum(url)
            },
            fail: function (err: any) {
                toast("预览失败")
            }
        }
    })
}

export function toast(msg: string, type: string = 'none') {
    uni.showToast({
        title: msg,
        icon: type,
        duration: 2000
    })
}

export function saveImageToPhotosAlbum(url: string) {
    uni.saveImageToPhotosAlbum({
        filePath: url,
        success: function () {
            toast("保存成功", "success")
        },
        fail: function (err: any) {
            toast("保存失败", "error")
        }
    });
}

/**
 * 合并背景图和二维码（简化版）
 * @param {string} bgUrl - 背景图URL
 * @param {string} qrUrl - 二维码URL
 * @returns {Promise<string>} - 返回临时图片路径（App端）或Base64（H5）
 */
export function mergeImage(bgUrl:string, qrUrl:string) {
    return new Promise(async (resolve, reject) => {
        // 1. 动态创建Canvas（避免依赖模板中的Canvas ID）
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            reject(new Error('Canvas 2D上下文初始化失败'));
            return;
        }

        try {
            // 2. 加载背景图
            const bgImg = await loadImage(bgUrl);
            canvas.width = bgImg.width;
            canvas.height = bgImg.height;
            ctx.drawImage(bgImg, 0, 0);

            // 3. 加载并绘制二维码（默认居中，大小为背景图的1/5）
            const qrImg = await loadImage(qrUrl);
            const qrSize = Math.min(bgImg.width, bgImg.height) / 5;
            const qrX = (bgImg.width - qrSize) / 2;
            const qrY = (bgImg.height - qrSize) / 2;
            ctx.drawImage(qrImg, qrX, qrY, qrSize, qrSize);

            // 4. 导出图片（区分平台）
            if (typeof uni !== 'undefined') {
                // UniApp环境：转临时文件
                uni.canvasToTempFilePath({
                    canvas,
                    success: (res) => resolve(res.tempFilePath),
                    fail: (err) => reject(new Error(`导出失败: ${err.errMsg}`)),
                });
            } else {
                // H5环境：直接返回Base64
                resolve(canvas.toDataURL('image/png'));
            }
        } catch (err) {
            reject(new Error(`图片合并失败: ${err.message}`));
        }
    });
}

export function loadImage(url: string) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = url;
        img.onload = () => resolve(img);
        img.onerror = () => reject(new Error("加载图片失败"));
    });
}
